package org.ucas.faker.web.fetcher;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ucas.faker.web.dao.FetchMapper;
import org.ucas.faker.web.fetcher.meta.FetchField;

import java.util.Map;

@Service
@Transactional
public class FetchExecutor {

  @Autowired
  private FetchMapper mapper;

  public FetchResult fetch(FetchRequest request) {
    if(request == null) return null;
    String sql = request.sql();
    FetchResult result = new FetchResult(mapper.execute(sql));

    if(result.data != null) {

      for (FetchField field : request.selects()) {
        if (field == null) continue;
        String key = field.name;
        if(key == null && field.column != null) key = field.column.alias;
        if(key == null && field.column != null) key = field.column.column;
        for (Map item : result.data)
          if(!item.containsKey(key)) item.put(key,null);
      }
    }
    return result;
  }

}
